package server

import (
	"broker-server/handler"
	"broker-server/internal/dao"
	"broker-server/user_session"
	"common-api/logs"
	"common-api/message"
	"common-api/process"
	"common-api/session"
	"net"
)

type TcpServer struct {
	net.Listener
}

func Start(addr string) (error, *TcpServer) {
	listen, err := net.Listen("tcp", addr)
	if err != nil {
		return err, nil
	}
	process.RegisterRequestProcess(message.RegisterRequestCode, &handler.RegisterHandler{
		dao.NewUserDao(),
		dao.NewTransaction(),
	})
	process.RegisterRequestProcess(message.PrivateChatRequestCode, &handler.PrivateChatHandler{})
	process.RegisterRequestProcess(message.HeartRequestBeatCode, &handler.HeartBeatHandler{})
	process.RegisterRequestProcess(message.LoginRequestCode, &handler.LoginHandler{dao.NewUserDao()})
	go func() {
		for {
			logs.Logger.Infof("start listen:%s", addr)
			conn, err := listen.Accept()
			if err != nil {
				logs.Logger.Errorf("accpet error:%v", err)
			}
			newSession := session.NewSession(conn)
			logs.Logger.Infof("accpet remote:%s - local:%s", conn.RemoteAddr().String(), conn.LocalAddr().String())
			go HandleConnection(newSession)
		}
	}()
	return err, &TcpServer{listen}
}

func HandleConnection(s *session.Session) {
	for {
		err := s.ReceiveMessage()
		if err != nil {
			s.Close()
			user_session.Close(s)
			logs.Logger.Errorf("receiver message error: %v", err)
			break // 发生错误时退出循环
		}
	}

}
